/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.GenConfig;
import me.zhengjie.domain.vo.TableInfo;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.mapper.GenConfigMapper;
import me.zhengjie.service.GenConfigService;
import me.zhengjie.service.GeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;

/**
 * @author Zheng Jie
 * @date 2019-01-14
 */
@Service
@RequiredArgsConstructor
@SuppressWarnings({"unchecked","all"})
public class GenConfigServiceImpl extends ServiceImpl<GenConfigMapper, GenConfig> implements GenConfigService {

    private final GenConfigMapper genConfigMapper;

    @Autowired
    private GeneratorService generatorService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String TEMPLATE_KEY_PREFIX = "gen_template:";

    @Override
    public GenConfig find(String tableName) {
        GenConfig genConfig = genConfigMapper.findByTableName(tableName);
        if(genConfig == null){
            return new GenConfig(tableName);
        }
        return genConfig;
    }

    @Override
    public GenConfig update(String tableName, GenConfig genConfig) {
        genConfig.setApiPath(generateApiPath(genConfig.getPath()));
        saveOrUpdate(genConfig);
        return genConfig;
    }

    private String generateApiPath(String path) {
        String separator = File.separator;
        String[] paths;
        String symbol = "\\";
        if (symbol.equals(separator)) {
            paths = path.split("\\\\");
        } else {
            paths = path.split(File.separator);
        }
        StringBuilder api = new StringBuilder();
        for (String pathPart : paths) {
            api.append(pathPart);
            api.append(separator);
            if ("src".equals(pathPart)) {
                api.append("api");
                break;
            }
        }
        return api.toString();
    }

    @Override
    public Object setTemplate(GenConfig genConfig) {
        genConfig.setApiPath(generateApiPath(genConfig.getPath()));
        try {
            String redisKey = TEMPLATE_KEY_PREFIX;
            if (stringRedisTemplate.hasKey(redisKey)) {
                stringRedisTemplate.delete(redisKey);
            }
            String jsonValue = objectMapper.writeValueAsString(genConfig);
            stringRedisTemplate.opsForValue().set(redisKey, jsonValue);
        } catch (JsonProcessingException e) {
            throw new BadRequestException("模板配置转换失败");
        }
        
        return genConfig;
    }

    @Override
    public GenConfig getTemplate(String tableName) {
        String redisKey = TEMPLATE_KEY_PREFIX;
        String jsonValue = stringRedisTemplate.opsForValue().get(redisKey);
        
        if (StrUtil.isBlank(jsonValue)) {
            return null;
        }
        try {
            GenConfig genConfig = objectMapper.readValue(jsonValue, GenConfig.class);
            genConfig.setTableName(tableName);

            Page<Object> page = new Page<>(1,10);
            List<TableInfo> tableInfos = generatorService.getTables(tableName, page).getContent();
            if(CollectionUtil.isEmpty(tableInfos)){
                throw new BadRequestException("表名不存在");
            }
            String remark = tableInfos.get(0).getRemark().toString();
            String suffix = StrUtil.isNotBlank(remark) ? remark.replace("表","") : "";
            genConfig.setApiAlias(suffix + "管理");
            return genConfig;
        } catch (JsonProcessingException e) {
            throw new BadRequestException("模板配置解析失败");
        }
    }
}
